package com.qiujie.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiujie.entity.StaffLeave;
import com.qiujie.enums.LeaveEnum;
import com.qiujie.entity.Leave;
import com.qiujie.mapper.LeaveMapper;
import com.qiujie.dto.Response;
import com.qiujie.dto.ResponseDTO;
import com.qiujie.mapper.StaffLeaveMapper;
import com.qiujie.util.EnumUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;


@Service
public class LeaveService extends ServiceImpl<LeaveMapper, Leave> {

    @Autowired
    private LeaveMapper leaveMapper;

    @Autowired
    private StaffLeaveMapper staffLeaveMapper;

    @Autowired
    private AnnualLeaveService annualLeaveService;

    public ResponseDTO add(Leave leave) {
        if (save(leave)) {
            return Response.success();
        }
        return Response.error();
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO addAnnualLeave(StaffLeave staffLeave) {
        // 参数校验
        if (staffLeave == null || staffLeave.getStaffId() == null || staffLeave.getDays() == null) {
            return Response.error("请求参数不完整");
        }

        try {
            // 年休假专属逻辑
            if (LeaveEnum.ANNUAL_LEAVE.equals(staffLeave.getTypeNum())) {
                // 获取最新余额
                ResponseDTO balanceResponse = annualLeaveService.getRemainingDays(staffLeave.getStaffId());
                if (balanceResponse.getCode() != 200) {
                    return balanceResponse;
                }

                Integer remainingDays = (Integer) balanceResponse.getData();
                if (remainingDays == null) {
                    return Response.error("年休假数据异常");
                }

                // 余额验证
                if (remainingDays < staffLeave.getDays()) {
                    return Response.error("年休假余额不足，剩余天数：" + remainingDays);
                }

                // 执行扣减
                ResponseDTO deductResponse = annualLeaveService.deductAnnualLeave(
                        staffLeave.getStaffId(),
                        staffLeave.getDays()
                );
                // 修正此处判断逻辑！！！
                if (deductResponse.getCode() != 200) {
                    return deductResponse; // 返回扣减失败信息
                }
            }

            // 保存记录
            return staffLeaveMapper.insert(staffLeave) > 0
                    ? Response.success()
                    : Response.error("申请记录保存失败");

        } catch (Exception e) {
            return Response.error("系统处理异常：" + e.getMessage());
        }
    }







    public ResponseDTO delete(Integer id) {
        if (removeById(id)) {
            return Response.success();
        }
        return Response.error();
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO deleteBatch(List<Integer> ids) {
        if (removeBatchByIds(ids)) {
            return Response.success();
        }
        return Response.error();
    }

    public ResponseDTO edit(Leave leave) {
        if (updateById(leave)) {
            return Response.success();
        }
        return Response.error();
    }

    public ResponseDTO query(Integer id) {
        Leave leave = getById(id);
        if (leave != null) {
            return Response.success(leave);
        }
        return Response.error();
    }

    public ResponseDTO queryByDeptIdAndTypeNum(Integer deptId, Integer typeNum) {
        QueryWrapper<Leave> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_id", deptId).eq("type_num", typeNum);
        Leave leave = getOne(queryWrapper);
        if (leave != null) {
            return Response.success(leave);
        }
        return Response.error();
    }

    public ResponseDTO setLeave(Leave leave) {
        QueryWrapper<Leave> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_id", leave.getDeptId()).eq("type_num", leave.getTypeNum());
        if (saveOrUpdate(leave, queryWrapper)) {
            return Response.success();
        }
        return Response.error();
    }

    public ResponseDTO queryByDeptId(Integer id) {
        List<Leave> list = this.leaveMapper.selectList(new QueryWrapper<Leave>().eq("dept_id", id));
        return Response.success(list);
    }



    public ResponseDTO queryByStaffIdAndDate(Integer staffId, String dateStr) {
        QueryWrapper<StaffLeave> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("staff_id", staffId)
                .le("start_date", dateStr)
                .ge("end_date", dateStr)
                .last("LIMIT 1"); // 确保只查一条记录
        StaffLeave staffLeave = staffLeaveMapper.selectOne(queryWrapper);
        return staffLeave != null ? Response.success(staffLeave) : Response.error();
    }




    /**
     * 获取所有请假类型
     * @return
     */
    public ResponseDTO queryAll() {
        return Response.success(EnumUtil.getEnumList(LeaveEnum.class));
    }






}
